//
//  InputBaseView.m
//  RomensBI
//
//  Created by 裴飞杨 on 2017/7/14.
//
//

#import "InputMainListView.h"

#import "InputBaseModel.h"

#import "InputTableViewHeaderView.h"
#import "InputOneLineTableViewCell.h"
#import "InputSwitchTableViewCell.h"
#import "InputTagTableViewCell.h"

#import "InputToolHelperClass.h"
#import "RomensSDK/UIView+IndexPath.h"
#import "RomensSDK/UITableView+ShowEmptyBodyData.h"

#import <RomensSDK/FormulaInfo.h>

#define sectionHeaderHeight 40
#define sectionFooterHeight 20

@interface InputMainListView()<UITableViewDelegate,UITableViewDataSource>{
    NSIndexPath *_indexPath;        /*点击的索引*/
    InputBaseViewModel *_viewModel;
    bool isRequest;
}
@property (nonatomic,strong)UITableView *mainTableView;  /*列表*/
@end
@implementation InputMainListView
#pragma mark - 初始化
-(instancetype)init{
    if (self = [super init]) {
        [self ctreatUI];
    }
    return self;
}
-(instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self ctreatUI];
    }
    return self;
}

-(void)setViewModel:(InputBaseViewModel *)viewModel {
    if (viewModel) {
        _viewModel = viewModel;
        //监听数组
        [self observeListDataArray];
    }
}
#pragma mark - 添加监听
-(void)observeListDataArray {
    [self.viewModel.dataModel addObserver:self
                               forKeyPath:ObserverKey
                                  options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionInitial
                                  context:nil];
}
#pragma mark - 移除监听
- (void)dealloc {
    if (self.viewModel.dataModel != nil)  {
        [self.viewModel.dataModel removeObserver:self forKeyPath:ObserverKey];
    }
}
-(void)ctreatUI {
    self.backgroundColor = BackGroundGrayColor;
    [self addSubview:self.mainTableView];
    
    NSDictionary *views = NSDictionaryOfVariableBindings(_mainTableView);
    
    [self addConstraints:[ToolHelper GetNSLayoutCont:views format:@"H:|[_mainTableView]|"]];
    [self addConstraints:[ToolHelper GetNSLayoutCont:views format:@"V:|-5-[_mainTableView]-|"]];
}
#pragma mark - 分析数据变化的情况
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    //数组发生变化
    if ([keyPath isEqualToString:ObserverKey]) {
        isRequest = true;
        NSMutableArray *dataArray = change[NSKeyValueChangeNewKey];
        //变化的数据是否存在，替换；不存在，加入。
        for (InputSectionModel *tmpe in dataArray) {
            if ([self.listModelArray containsObject:tmpe]) {
                NSUInteger index = [self.listModelArray indexOfObject:tmpe];
                [self.listModelArray replaceObjectAtIndex:index withObject:tmpe];
            } else {
                [self.listModelArray addObject:tmpe];
            }
        }
        [self.mainTableView reloadData];
//        if (animated) {
//            [self animateTableView];
//        }
    }
}
#pragma mark - 展示TableView动画
-(void)animateTableView {
    CGAffineTransform transform = CGAffineTransformMakeTranslation(0.0, -(FULL_HEIGHT - 20.0));
    [self.mainTableView.layer setAffineTransform:transform];
    [UIView animateWithDuration:0.8
                          delay:0.0
         usingSpringWithDamping:0.75
          initialSpringVelocity:0.0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^
    {
        [self.mainTableView.layer setAffineTransform:CGAffineTransformIdentity];
    }
                     completion:nil];
}
#pragma mark - lazy

-(UITableView *)mainTableView {
    if (!_mainTableView) {
        _mainTableView = [[UITableView alloc] init];
        _mainTableView.delegate = self;
        _mainTableView.dataSource = self;
        _mainTableView.backgroundColor = BackGroundGrayColor;
        _mainTableView.showsVerticalScrollIndicator = NO;
        _mainTableView.translatesAutoresizingMaskIntoConstraints = NO;
        if (@available(iOS 11.0, *)) {
            _mainTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _mainTableView.estimatedRowHeight = 0;
            _mainTableView.estimatedSectionFooterHeight = 0;
            _mainTableView.estimatedSectionHeaderHeight = 0;
        }
        //取消tableView悬停
        _mainTableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,self.frame.size.width, sectionHeaderHeight)];
        _mainTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,self.frame.size.width, sectionHeaderHeight)];
        _mainTableView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, -sectionHeaderHeight, 0);
    }
    return _mainTableView;
}

-(NSMutableArray *)listModelArray {
    if (!_listModelArray) {
        _listModelArray = [[NSMutableArray alloc] init];
    }
    return _listModelArray;
}

#pragma mark - Table view data source
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (isRequest) {
        [tableView tableViewDisplayWitMsg:nil Message:@"暂无数据,请稍后重试" ifNecessaryForRowCount:self.listModelArray.count];
    }
    return self.listModelArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    InputSectionModel *sectionModel = self.listModelArray[section];
    if (sectionModel.close) {
        return 0;
    } else {
        return sectionModel.nodes.count ? sectionModel.nodes.count : 0;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    InputSectionModel *sectionModel    = self.listModelArray[indexPath.section];
    InputCellModel    *model           = sectionModel.nodes[indexPath.row];
    NSString          *cellIndentifier = model.cellIdentifier;
    //隐藏Cell
    if (model.ishidden || isEmptyString(cellIndentifier)) {
        return [[UITableViewCell alloc] init];
    }
    UITableViewCell *cell = [tableView  dequeueReusableCellWithIdentifier:cellIndentifier];
    if (cell == nil) {
        cell = [[NSClassFromString(cellIndentifier) alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
        //双击手势
        UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTouch:)];
        [gesture setNumberOfTapsRequired:2];
        [cell addGestureRecognizer:gesture];
        //监听UISWith
        if ([cell isKindOfClass:[InputSwitchTableViewCell class]]) {
            [((InputSwitchTableViewCell*)cell).switchView addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
        }
    }
    cell.c_NSIndexPath = indexPath;
    if ([cell isKindOfClass:[InputBaseTableViewCell class]]) {
        ((InputBaseTableViewCell*)cell).titleLabel.text = model.nameCaption;
        //是否是必填项
        ((InputBaseTableViewCell*)cell).showPointIcon = model.isMustInput;
        //是否是高亮
        ((InputBaseTableViewCell*)cell).titleHighlight = model.isHighlight;
    }
    // 多行、单行Cell
    if ([cell isKindOfClass:[InputMultiLineTableViewCell class]]) {
        //右侧图片是否隐藏
        ((InputRightImageTableViewCell*)cell).hiddenImage = self.viewModel.dataModel.editInput && !model.isLock;
        [(InputRightImageTableViewCell*)cell setNeedsUpdateConstraints];
        [(InputRightImageTableViewCell*)cell updateConstraintsIfNeeded];
        [self creatBaseCellValue:(InputOneLineTableViewCell *)cell WithIndex:indexPath];
    //带UISwitch控件Cell
    } else if ([cell isKindOfClass:[InputSwitchTableViewCell class]]) {
        ((InputSwitchTableViewCell*)cell).switchView.c_NSIndexPath = indexPath;
        ((InputSwitchTableViewCell*)cell).switchView.enabled = self.viewModel.dataModel.editInput && !model.isLock;
        ((InputSwitchTableViewCell*)cell).switchView.on = [model.inputDetail boolValue];
        if (model.boolItems.count >= 2) {
            ((InputSwitchTableViewCell*)cell).switchView.offText = model.boolItems[0];
            ((InputSwitchTableViewCell*)cell).switchView.onText = model.boolItems[1];
        }
    
    }
    return cell;
}
//cellValue赋值
-(void)creatBaseCellValue:(InputOneLineTableViewCell *)cell WithIndex:(NSIndexPath *)index {
    InputSectionModel *sectionModel = self.listModelArray[index.section];
    InputCellModel *model = sectionModel.nodes[index.row];
    
    if (isEmptyString(model.inputDetail)) {
        ((InputMultiLineTableViewCell*)cell).valueLabel.textColor = [UIColor lightGrayColor];
        ((InputMultiLineTableViewCell*)cell).valueLabel.text = @"";
        
    } else {
        ((InputMultiLineTableViewCell*)cell).valueLabel.textColor = [UIColor blackColor];
        //公式计算
        if (!isEmptyString(model.formula)) {
            [self formulaCalculation:index];
        }
        //格式化数据 如 1.今天是{Value::yyyy年MM月dd日} ==> 今天是2018年07月01日 2.
        NSString *format = model.inputFormat;
        NSString *formatString = model.formatString;
        NSString *inputDetail  = model.inputDetail;
        //不需要格式化
        if ([format isEqualToString:NotFormat] || isEmptyString(format)) {
            cell.valueLabel.text = inputDetail;
            //一般替换
        } else if ([format isEqualToString:NormalFormat]) {
            cell.valueLabel.text = [formatString stringByReplacingOccurrencesOfString:NormalFormat withString:inputDetail];
            //有具体的解析方式
        } else {
            NSString *formatDetail = [InputToolHelperClass formatInputDetailWithInputType:model.inputtype WithDetail:inputDetail WithFormat:format];
            cell.valueLabel.text = [formatString stringByReplacingOccurrencesOfString:[InputToolHelperClass handleFormatString:formatString] withString:formatDetail];
        }
    }
}

//公式计算
-(void)formulaCalculation:(NSIndexPath *)index {
    InputSectionModel *sectionModel = self.listModelArray[index.section];
    InputCellModel *model = sectionModel.nodes[index.row];
    NSMutableDictionary *referenceDict = [[NSMutableDictionary alloc] init];
    /*
     ** 如，计算BMI。
     ** 查找引用列。
     ** reference包括'HEIGHT'、'WEIGHT'，从模板中找到输入的值'180'，'60'
     ** 拼接为 @{"HEIGHT": 180, "WEIGHT":60}
     ** 然后根据公式计算
     ** 计算成功后返回 @{"BMI": 20},并找到BMI并赋值
     */
    for (NSString *referenceKey in model.reference) {
        for (InputCellModel *cellModel in sectionModel.nodes) {
            if ([cellModel.codeKey isEqualToString:referenceKey]) {
                referenceDict[referenceKey] = cellModel.inputDetail;
                break;
            }
        }
    }
    FormulaInfo *formula = [[FormulaInfo alloc] init:referenceDict formula:model.formula];
    //计算并赋值
    if ([formula Calc]) {
        NSDictionary *dict = [formula resultDict];
        for (NSString *key in dict.allKeys) {
            for (InputCellModel *cellModel in sectionModel.nodes) {
                if ([cellModel.codeKey isEqualToString:key]) {
                    cellModel.inputDetail = dict[key];
                    break;
                }
            }
        }
    }
}
#pragma mark - UITableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    InputSectionModel *sectionModel = self.listModelArray[indexPath.section];
    InputCellModel    *cellModel    = sectionModel.nodes[indexPath.row];
    //隐藏的cell 或者无定义的cell
    if (cellModel.ishidden || isEmptyString(cellModel.cellIdentifier)) {
        return 0;
    } else {
        if ([cellModel.cellIdentifier isEqualToString:MultiLineCellIdentifier]) {
            tableView.estimatedRowHeight = 70;
        } else {
            tableView.estimatedRowHeight = 40;
        }
        return UITableViewAutomaticDimension;
    }
}
//HeaderFooterView
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return sectionHeaderHeight;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    InputSectionModel *model = self.listModelArray[section];
    static NSString *identifier = @"headerView";
    InputTableViewHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:identifier];
    if (!headerView) {
        headerView = [[InputTableViewHeaderView alloc] initWithReuseIdentifier:identifier];
        UITapGestureRecognizer *tapGeture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(touchHeaderView:)];
        [headerView addGestureRecognizer:tapGeture];
    }
    [self creatHeaderViewDataWithView:headerView WithModel:model];
    headerView.tag = section;
    return headerView;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UITableViewHeaderFooterView *footerView = [[UITableViewHeaderFooterView alloc] init];
    return footerView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return sectionFooterHeight;
}
//headerView footerView 背景颜色
-(void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section{
    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
    [header.contentView setBackgroundColor: BackGroundGrayColor];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    _indexPath = indexPath;
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self.viewModel pushInputViewWithIndexPath:indexPath];
}
#pragma mark - 双击
-(void)doubleTouch:(UITapGestureRecognizer *)tapGesture {
    UITableViewCell *touchView = (UITableViewCell *)tapGesture.view;
    [self.viewModel showDetailVauleWithCell:touchView];
}
#pragma mark - headerView赋值
-(void)creatHeaderViewDataWithView:(InputTableViewHeaderView *)header WithModel:(InputSectionModel *)model{
    header.titleLabel.text      = model.nameCaption;
    header.rightImageView.image = nil;
    if (model.nodes.count == 0) {
        model.close = YES;
    }
    //关闭
    if (model.close) {
        header.rightImageView.image = [[UIImage imageNamed:GetBundleImage(@"RomensUISDK.bundle/InputView", @"ic_arrow_down_white")] imageWithColor:HEXCOLOR(0xdfdfdfff)];
        //打开
    } else{
        header.rightImageView.image = [[UIImage imageNamed:GetBundleImage(@"RomensUISDK.bundle/InputView", @"ic_arrow_up_white")] imageWithColor:HEXCOLOR(0xdfdfdfff)];
    }
}
#pragma mark - 点击HeaderView
-(void)touchHeaderView: (UITapGestureRecognizer *)sender{
    NSInteger         section = sender.view.tag;
    InputSectionModel *model  = self.listModelArray[section];
    //折叠Cell
    if (model.nodes.count != 0) {
        model.close = !model.close;
        [UIView performWithoutAnimation:^{
            [self.mainTableView reloadSections:[NSIndexSet indexSetWithIndex:section]
                              withRowAnimation:UITableViewRowAnimationAutomatic];
        }];
    //跳转新界面
    } else {
        [self.viewModel pushNewInputViewControllerWithSection:section];
    }
}
#pragma mark - 监听UISwitch点击事件
-(void)switchAction: (id)sender {
    [self.viewModel switchAction:sender];
}
#pragma mark - 解决tableViewCell 右移问题
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}
@end

